// index.js
// const app = getApp()
const { envList } = require('../../envList.js');

Page({
  data: {
    sayShow:false,
    animation: {},
    showModalStatus: false,
    button_onclick:'sign_in',
    nowDate:'',
    envId: 'cloud1-3g5swxbmab7098c9',
    sign_in:"签到",
    sign_in_color:"#07c160",
    showUploadTip: false,

    powerList: [{
      title: '数据库',
      tip: '安全稳定的文档型数据库',
      showItem: true,
      item: [{
        title: '完成任务',
        page: 'toCompleteMission'
      }, {
        title: '兑换奖励',
        page: 'toExchangeRewards'
      }, {
        title: '查询记录',
        page: 'selectRecord'
      },
      {
        title: '任务管理',
        page: 'updateMission'
      },
      {
        title: '奖励管理',
        page: 'updateRewards'
      }
    ]
    }],
    envList,
    selectedEnv: envList[0],
    haveCreateCollection: false,
    userIntegral: 0,
    userName: '',
    operatorType: {
      COMPLETE_MISSION: 'complete mission',
      EXCHANGE_REWARDS: 'exchange rewards'
    }
  },

  onLoad(){
    var nowDate = this.formatDateTime();
    var towDaysBetween = this.GetNumberOfDays('2019-09-20',nowDate);

    wx.showToast({
      title: '大🐻正在赶来...',
      mask: true,
      icon: 'loading'
      })

    console.log(towDaysBetween);
    this.setData({
      nowDate:nowDate,
      towDaysBetween:towDaysBetween
    })

    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.envId
      },
      data: {
        type: 'add_sign_in',
        data: {
          nowdate:nowDate
        }
      }
    }).then((resp)=>{
      console.log(this.data.envId)
      console.log(nowDate)
      console.log('resp', resp)
      const sign_inData = resp.result.data.reverse();
      console.log('sign_inData', sign_inData)

      if(sign_inData.length > 0)
      {
        console.log('今天已签到')
        this.setData({
          sign_in:"已签到",
          sign_in_color:"#c3c9c7",
          button_onclick:''
        })
      }
      // wx.hideLoading();
    })

 
    this.resetMission()
  },

  onShow(){
    this.selectUser();

     // 1: 创建动画实例animation:
     var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    })
    this.animation = animation
    var next = true;
    //连续动画关键步骤
    setInterval(function () {
      //2: 调用动画实例方法来描述动画
      if (next) {
        // animation.translateX(4).step();
        animation.rotate(19).step()
        next = !next;
      } else {
        // animation.translateX(-4).step();
        animation.rotate(-19).step()
        next = !next;
      }
      //3: 将动画export导出，把动画数据传递组件animation的属性 
      this.setData({
        animation: animation.export()
      })
    }.bind(this), 900)
  },

  onClickPowerInfo(e) {
    const index = e.currentTarget.dataset.index;
    const powerList = this.data.powerList;
    powerList[index].showItem = !powerList[index].showItem;
    if (powerList[index].title === '数据库' && !this.data.haveCreateCollection) {
      this.onClickDatabase(powerList);
    } else {
      this.setData({
        powerList
      });
    }
  },

  onChangeShowEnvChoose() {
    wx.showActionSheet({
      itemList: this.data.envList.map(i => i.alias),
      success: (res) => {
        this.onChangeSelectedEnv(res.tapIndex);
      },
      fail (res) {
        console.log(res.errMsg);
      }
    });
  },

  onChangeSelectedEnv(index) {
    if (this.data.selectedEnv.envId === this.data.envList[index].envId) {
      return;
    }
    const powerList = this.data.powerList;
    powerList.forEach(i => {
      i.showItem = false;
    });
    this.setData({
      selectedEnv: this.data.envList[index],
      powerList,
      haveCreateCollection: false
    });
  },

  jumpPage(e) {
    if (e.currentTarget.dataset.page == 'updateMission' || e.currentTarget.dataset.page == 'updateRewards' )
    {
      var listthis = this;
      wx.showActionSheet({
        itemList: ['身份：大熊', '身份：橙子'],
        success(res) {
          console.log(res.tapIndex)
          if(res.tapIndex == 0)
          {
            console.log('熊')
            wx.navigateTo({
              url: `/pages/${e.currentTarget.dataset.page}/index?envId=${listthis.data.selectedEnv.envId}`,
            });
          }
          if(res.tapIndex == 1)
          {
            console.log('橙')
            wx.showToast({
              title: '只能大熊操作哦。',
              icon: 'none',//当icon：'none'时，没有图标 只有文字
              duration: 2000
            })
          }
        },
        fail(res) {
         console.log(res.errMsg)
        },
      })
    }
    else
    {
      wx.navigateTo({
        url: `/pages/${e.currentTarget.dataset.page}/index?envId=${this.data.selectedEnv.envId}`,
      });
    }

  
  },

  onClickDatabase(powerList) {
    wx.showLoading({
      title: '',
    });
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.selectedEnv.envId
      },
      data: {
        type: 'createCollection'
      }
    }).then((resp) => {
      if (resp.result.success) {
        this.setData({
          haveCreateCollection: true
        });
      }
      this.setData({
        powerList
      });
      wx.hideLoading();
    }).catch((e) => {
      console.log(e);
      this.setData({
        showUploadTip: true
      });
      wx.hideLoading();
    });
  },

  selectUser() {
    wx.cloud.callFunction({
     name: 'quickstartFunctions',
     config: {
       env: this.data.envId
     },
     data: {
       type: 'selectUser',
     }
   }).then((resp) => {
     this.setData({
      userIntegral: resp.result.data[0].user_integral,
      userName: resp.result.data[0].user_name
     })
   }).catch((e) => {
  });
 },

  resetMission() {
    wx.cloud.callFunction({
        name: 'quickstartFunctions',
        config: {
          env: this.data.envId
        },
        data: {
          type: 'selectOperator'
        }
      }).then((resp) => {
        const operatorData = resp.result.data.reverse();
        let lastMissionDate;
        operatorData.some(item => {
          if(item.operator_type === this.data.operatorType.COMPLETE_MISSION){
            lastMissionDate = new Date(item.operator_time).getDate();
            return true
          }
          return false
        })
        const currentDate = new Date().getDate();
        console.log('lastMissionDate', lastMissionDate)
        console.log('currentDate', currentDate)
        if (lastMissionDate !== currentDate){
          console.log('resetMission')
          wx.cloud.callFunction({
            name: 'quickstartFunctions',
            config: {
              env: this.data.envId
            },
            data: {
              type: 'resetMission'
            }
          }).then((resp) => {

          })
        }
        
    }).catch((e) => {
    });
  },

  sign_in(){
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: this.data.envId
      },
      data: {
        type: 'add_signINdate',
        data:{
          nowdate:this.data.nowDate
        }
      }
    }).then(resp => {

      wx.cloud.callFunction({
        name: 'quickstartFunctions',
        config: {
          env: this.data.envId
        },
        data: {
          type: 'updateUser',
          data: {
            integral: 50
          }
        }
      }).then(resp => {
        wx.showToast({
          title: '签到成功！获得50积分。新的一天也有在想宝哦❤',
          icon: 'none',//当icon：'none'时，没有图标 只有文字
          duration: 3000
        })
        this.setData({
          sign_in:"已签到",
          sign_in_color:"#c3c9c7",
          button_onclick:''
        })

        this.selectUser();
      })

      
    })
  },

  clickTree(){
    const clickTreeThis = this;
    this.setData({
      sayShow:true
    });
    setTimeout(function(){
      clickTreeThis.setData({
        sayShow:false
      });
    },3000)
  },
  
  formatDateTime() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h=h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    return y+'-'+m + '-' + d;
  },

  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function (currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });
    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;
    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();
    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })
    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })
      //关闭  
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
  },

  GetNumberOfDays(date1,date2){//获得天数
    //date1：开始日期，date2结束日期
    var a1 = Date.parse(new Date(date1));
    var a2 = Date.parse(new Date(date2));
    var day = parseInt((a2-a1)/ (1000 * 60 * 60 * 24));//核心：时间戳相减，然后除以天数
    return day
}

});



